package com.jt.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private RemoteUserService remoteUserService;

    /**
     * 基于用户名获取数据库中的用户信息
     * @Date 16:58 2021/11/25
     * @Param [username]
     * @return org.springframework.security.core.userdetails.UserDetails
     * @throws UsernameNotFoundException
     **/
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //基于feign方式获取远程数据并封装
        //1、基于用户名获取用户信息
        com.jt.pojo.User user = remoteUserService.selectUserByUsername(username);
        if (user==null){
            throw new UsernameNotFoundException("用户不存在");
        }
        //2、基于用户ID查询用户权限
        List<String> permissions = remoteUserService.selectUserPermissions(user.getId());
        log.info("permissions {}",permissions.toString());
        //3、对查询结果进行封装并返回交给认证中心
        return new User(user.getUsername(),
                        user.getPassword(),
                        AuthorityUtils.createAuthorityList(permissions.toArray(new String[]{})));
    }
}
